package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsAdminMapper;
import com.qf.mapper.DtsPermissionMapper;
import com.qf.mapper.DtsRoleMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.pojo.DtsRole;
import com.qf.service.DtsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Service
public class DtsRoleServiceImpl implements DtsRoleService {

    @Autowired
    DtsRoleMapper roleMapper;

    @Override
    public Set<String> findRolesByRoleIds(Integer[] roleIds) {
        LambdaQueryWrapper<DtsRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DtsRole::getId, roleIds).select(DtsRole::getName);

        List<DtsRole> roles = roleMapper.selectList(wrapper);
        //使用lambda 把list中的数据 存储到set集合中
        //stream: 流化
        //map : 映射关系
        //collect： 指定要转换的类型
        //role 表示list中的每一个元素
        Set<String> roleNames = roles.stream().map(role -> {
            return role.getName();
        }).collect(Collectors.toSet());

        return roleNames;
    }

    @Override
    public List<DtsRole> findAll() {
        List<DtsRole> roles = roleMapper.selectList(null);
        return roles;
    }

    @Override
    public IPage<DtsRole> queryPage(Integer page, Integer limit, String sort, String order, String rolename) {
        //分页参数
        IPage<DtsRole> ipage = new Page<>(page, limit);
        //其他条件
        QueryWrapper<DtsRole> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(rolename)){
            wrapper.like("name", rolename);
        }

        wrapper.eq("deleted", false);

        //排序条件
        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)){
            if(order.equals("desc")){
                wrapper.orderByDesc(sort);
            }else{
                wrapper.orderByAsc(sort);
            }
        }

        roleMapper.selectPage(ipage ,wrapper );

        return ipage;
    }

    @Override
    public DtsRole insert(DtsRole role) {
        role.setAddTime(new Date());
        role.setUpdateTime(new Date());
        role.setDeleted(false);
        role.setEnabled(true);
        roleMapper.insert(role);
        return role;
    }

    @Override
    public boolean checkRole(String name) {
        LambdaQueryWrapper<DtsRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsRole::getName, name);

        Integer count = roleMapper.selectCount(wrapper);

        return count != 0;
    }

    @Override
    public void deleteById(Integer id) {

        roleMapper.deleteById(id);
    }

    @Override
    public DtsRole update(DtsRole role) {
        role.setUpdateTime(new Date());
        roleMapper.updateById(role);
        return role;
    }

    @Autowired
    DtsAdminMapper adminMapper;

    @Autowired
    DtsPermissionMapper permissionMapper;

    @Override
    public boolean checkRelationRole(Integer id) {
        //查询是否被权限表关联
        LambdaQueryWrapper<DtsPermission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsPermission::getRoleId, id);

        Integer count = permissionMapper.selectCount(wrapper);
        if(count > 0){
            return false;
        }

        //把所有的管理查询查询出来，判断管理员的角色id中是否存在该 角色id， 如果存在返回false
        List<DtsAdmin> adminList = adminMapper.selectList(null);
        for (DtsAdmin admin : adminList) {
            if(admin.getRoleIds() != null && admin.getRoleIds().length > 0){
                for (Integer roleId : admin.getRoleIds()) {
                    if(roleId == id){
                        return false;
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean checkIsSuperManager(Integer roleId) {
        DtsRole role = roleMapper.selectById(roleId);
        if(role.getName() != null && role.getName().equals("超级管理员")){
            return true;
        }
        return false;
    }


    @Override
    public void updatePermissions(Integer roleId, List<String> permissions) {
        //1. 删除该角色的所有权限
        LambdaQueryWrapper<DtsPermission>  wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsPermission::getRoleId, roleId);
        permissionMapper.delete(wrapper);

        //2. 添加角色和权限新的关系
        if(permissions != null && permissions.size() > 0){
            for (String permission : permissions) {
                DtsPermission perm  = new DtsPermission();
                perm.setRoleId(roleId);
                perm.setPermission(permission);
                perm.setAddTime(new Date());
                perm.setUpdateTime(new Date());
                perm.setDeleted(false);

                permissionMapper.insert(perm);
            }
        }
    }
}
